package com.kate.mall.common.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class Json2StringTypeHandler extends BaseTypeHandler<String[]> {
  ObjectMapper objectMapper = new ObjectMapper();

  //程序中(json字符串数组)---------->数据库（字符串）
  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
    ps.setString(i, object2String(parameter));//java：["长度","宽度"]     jdbc: "["长度","宽度"]"----varchar
  }
  //数据库（字符串）---------->程序中(json字符串数组)
  @Override
  public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
    return string2Object(rs.getString(columnName)) ;
  }
  //数据库（字符串）---------->程序中(json字符串数组)
  @Override
  public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return string2Object(rs.getString(columnIndex)) ;
  }
  //数据库（字符串）---------->程序中(json字符串数组)
  @Override
  public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return string2Object(cs.getString(columnIndex)) ;
  }
  //方法1:json字符串数组--->字符串
  public String object2String(String[] obj){
    try {
      return objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
    return null;
  }

  //方法2:字符串--->json字符串数组
  public String[] string2Object(String value){
    try {
      return objectMapper.readValue(value,String[].class);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
    return null;
  }

  public static void main(String[] args) throws JsonProcessingException {
    String[] values= {"abc","def"};
    String json = new ObjectMapper().writeValueAsString(values);
    System.out.println(json);

  }
}